package com.ruoyi.common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.LineHandler;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.extra.ftp.Ftp;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.net.ftp.FTPFile;

import java.io.File;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Set;

@Slf4j
public class ErpFileAnalysisUtil {
    private final static String host = "115.29.168.41";
    private final static int port = 21;

    private static Ftp ftp;

    /**
     * 文件夹下所有文件
     *
     * @return
     */
    public static List<FTPFile> getFiles(Set<String> suitableFilePrefix) {
        try {
            ftp = new Ftp(host, port, "qdbookcity", "qdbookcity@2020");

            FTPFile[] ftpFiles = ftp.lsFiles("/", ftpFile -> {
                Calendar timestamp = ftpFile.getTimestamp();

                // 取一天内的文件
                if (timestamp.getTimeInMillis() + 24L * 60 * 60 * 1000 > System.currentTimeMillis()) {
                    String name = ftpFile.getName();

                    return suitableFilePrefix.contains(name.split("_")[0]);
                }
                return false;
            }).toArray(new FTPFile[0]);

            log.info("ftpFiles: {}", JSON.toJSONString(ftpFiles));

            return Arrays.asList(ftpFiles);
        } catch (Exception e) {
            log.info("getFiles: {}", ExceptionUtils.getStackTrace(e));
        } finally {
            ErpFileAnalysisUtil.closeFtp(ftp);
        }
        return Lists.newArrayList();
    }

    public static void analysisFile(String fileName, LineHandler lineHandler) {
        log.info("analysisFile : {}", fileName);
        try {
            ftp = new Ftp(host, port, "qdbookcity", "qdbookcity@2020");
            // 下载远程文件
            File file = FileUtil.file(fileName);
            ftp.download("/", fileName, file);

            FileReader fileReader = new FileReader(file);

            fileReader.readLines(lineHandler);

            // 关闭连接
            ftp.close();
        } catch (Exception e) {
            log.info("analysisFile: {}", ExceptionUtils.getStackTrace(e));
        } finally {
            ErpFileAnalysisUtil.closeFtp(ftp);
        }
    }

    private static void closeFtp(Ftp localFtp) {
        try {
            localFtp.close();
        } catch (Exception e) {
            log.info("closeFtp: {}", ExceptionUtils.getStackTrace(e));
        }
    }
}
